<template>
	<BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
		<BasicForm @register="registerForm" />
	</BasicModal>
</template>

<script lang="ts">
	import { defineComponent, ref, computed, unref } from 'vue';
	import { BasicModal, useModalInner } from '/@/components/Modal';
	import { BasicForm, useForm } from '/@/components/Form/index';
	import { passwordFormSchema } from './user.data';
	import { save } from '/@/api/system/user';
	import md5 from 'js-md5';
	export default defineComponent({
		name: 'AccountModal',
		components: { BasicModal, BasicForm },
		emits: ['success', 'register'],
		setup(_, { emit }) {
			const isUpdate = ref(true);

			const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
				labelWidth: 100,
				baseColProps: { span: 24 },
				schemas: passwordFormSchema,
				showActionButtonGroup: false,
				actionColOptions: {
					span: 23,
				},
			});

			const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
				resetFields();
				setModalProps({
					confirmLoading: false,
					title: `给账号【${data.record.username}(${data.record.nickname})】设置密码`,
				});
				isUpdate.value = !!data?.isUpdate;

				if (unref(isUpdate)) {
					setFieldsValue({
						...data.record,
					});
				}
			});

			const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '设置密码'));

			async function handleSubmit() {
				try {
					setModalProps({ confirmLoading: true });
					const values = await validate();
					values.password = md5(values.passwordNew);
					delete values.passwordNew;
					delete values.confirmPassword;
					save(values);
					closeModal();
				} finally {
					setModalProps({ confirmLoading: false });
				}
			}
			return { registerModal, registerForm, getTitle, handleSubmit };
		},
	});
</script>